package com.代理模式.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 代理对象工厂
 */
public class ProxyFactory implements MethodInterceptor {

    private Trainstation trainstation=new Trainstation();
    /**
     *获取代理类：此代理类就是Trainstation的子类
     */
    public Trainstation getProxyObject(){
        /**
         * 创建Enhancer对象，此对象就类似于JDK代理中的Proxy类
         */
        Enhancer enhancer=new Enhancer();
        //设置父类的字节码对象
        enhancer.setSuperclass(Trainstation.class);
        //设置回调函数
        enhancer.setCallback(this);
        //创建代理对象
        Trainstation trainstation= (Trainstation) enhancer.create();
        return trainstation;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置增强..................");
        //调用目标对象的方法
        Object returnObject = method.invoke(trainstation, objects);
        System.out.println("后置增强..................");
        return returnObject;
    }
}
